package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * mybatis拦截器，自动注入创建人、创建时间
 * @Author scott
 * @Date  2019-01-19
 *
 */
@Slf4j
@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MybatisInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		String sqlId = mappedStatement.getId();
		log.debug("------sqlId------" + sqlId);
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		Object parameter = invocation.getArgs()[1];
		log.debug("------sqlCommandType------" + sqlCommandType);

		if (parameter == null) {
			return invocation.proceed();
		}
//		//客户申请试用无人员
//		if(sqlId.contains("SaasRequisitionMapper")||sqlId.contains("SysOperLogMapper")||sqlId.contains("SysLogininforMapper")){
//			return invocation.proceed();
//		}

		if (SqlCommandType.INSERT == sqlCommandType) {
			Field[] fields = getAllFields(parameter);
			Authentication authentication = SecurityUtils.getAuthentication();
			LoginUser user = null;
			if (authentication!=null){
				user = (LoginUser) authentication.getPrincipal();
			}
			for (Field field : fields) {
//				log.debug("------field.name------" + field.getName());
				try {
//					20240617  部分表用createBy字段表示创建人。 修复报错问题
					if ("creator".equals(field.getName()) || "createBy".equals(field.getName())) {
						log.debug("------field.name------" + field.getName());
						if (user != null){
							String username = user.getUsername();
							field.setAccessible(true);
							Object localCreateBy = field.get(parameter);
							field.setAccessible(false);
							if (localCreateBy == null || "".equals(localCreateBy)) {
								// 登录人用户名
								log.debug("------field.val------" + username);
								field.setAccessible(true);
								field.set(parameter, username);
								field.setAccessible(false);
							}
						}
					}
					if ("creator_id".equals(field.getName()) || "createById".equals(field.getName())) {
						log.debug("------field.name------" + field.getName());
						if (user != null){
							Long userId = user.getUserId();
							field.setAccessible(true);
							Object localCreateBy = field.get(parameter);
							field.setAccessible(false);
							if (localCreateBy == null || "".equals(localCreateBy)) {
								// 登录人账号
								field.setAccessible(true);
								log.debug("------field.val------" + userId);
								field.set(parameter, userId);
								field.setAccessible(false);
							}
						}
					}
					// 注入创建时间
					if ("gmtCreate".equals(field.getName()) || "createTime".equals(field.getName())) {
						LocalDateTime localDateTime = LocalDateTime.now();
						log.debug("------field.name------" + field.getName());
						log.debug("------field.val------" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
						if (field.getType() == Date.class) {
                            field.setAccessible(true);
                            field.set(parameter, new Date());
                            field.setAccessible(false);
                        }else {
							field.setAccessible(true);
							field.set(parameter, localDateTime);
							field.setAccessible(false);
						}
					}

				} catch (Exception e) {
					log.debug("------err field.name------" + field.getName());

				}
			}
		}
//		if (SqlCommandType.UPDATE == sqlCommandType) {
//			LoginUser sysUser = SecurityUtils.getLoginUser();
//			Field[] fields = null;
//			if (parameter instanceof ParamMap) {
//				ParamMap<?> p = (ParamMap<?>) parameter;
//
//                String et = "et";
//				if (p.containsKey(et)) {
//					parameter = p.get(et);
//				} else {
//					parameter = p.get("param1");
//				}
//				if (parameter == null) {
//					return invocation.proceed();
//				}
//
//
//				fields = getAllFields(parameter);
//			} else {
//				fields = getAllFields(parameter);
//			}
//
//			for (Field field : fields) {
//				log.debug("------field.name------" + field.getName());
//				try {
//					if ("updateBy".equals(field.getName())) {
//						//获取登录用户信息
//						if (sysUser != null) {
//							// 登录账号
//							field.setAccessible(true);
//							field.set(parameter, sysUser.getUsername());
//							field.setAccessible(false);
//						}
//					}
//					if ("updateTime".equals(field.getName())) {
//						field.setAccessible(true);
//						field.set(parameter, new Date());
//						field.setAccessible(false);
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}




	/**
	 * 获取类的所有属性，包括父类
	 *
	 * @param object
	 * @return
	 */
	public static Field[] getAllFields(Object object) {
		Class<?> clazz = object.getClass();
		List<Field> fieldList = new ArrayList<>();
		while (clazz != null) {
			fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
			clazz = clazz.getSuperclass();
		}
		Field[] fields = new Field[fieldList.size()];
		fieldList.toArray(fields);
		return fields;
	}

}
